<script setup lang="ts">
import { computed, reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { $t } from '@/locales';
import { localStg } from '@/utils/storage';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { REQUEST } from '@/api/request';
import { setToken } from '@/plugins/cookie';
import { router } from '@/router';
const message = useMessage();
defineOptions({
  name: 'PwdLogin'
});
const { formRef, validate } = useNaiveForm();
const loading = ref(false);
interface FormModel {
  mobile: string;
  password: string;
}

const model: FormModel = reactive({
  mobile: '',
  password: ''
});
//  mobile: 'LUCKGIFT',
//   password: '01124083898'
const rules = computed<Record<keyof FormModel, App.Global.FormRule[]>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { formRules } = useFormRules();

  return {
    mobile: formRules.mobile,
    password: formRules.pwd
  };
});

async function handleSubmit() {
  await validate();
  // await authStore.login(model.mobile, model.password);
  loading.value = true;
  REQUEST.POST('LOGIN', {
    mobile: model.mobile,
    password: model.password
  }).then((res: any) => {
    loading.value = false;
    if (res.status === 200) {
      localStg.set('token', res.data.token);
      setToken(res.data.token);

      const obj: any = {
        userName: model.mobile,
        name: res.data.name,
        userId: res.data.userId,
        password: model.password,
        level: res.data.level
      };
      window.localStorage.setItem('userInfo', JSON.stringify(obj));
      message.success('登录成功！');
      setTimeout(() => {
        window.location.reload();
        router.push({ path: '/home' });
      }, 2000);
    }
  });
}
</script>

<template>
  <NForm ref="formRef" :model="model" :rules="rules" size="large" :show-label="false" @keyup.enter="handleSubmit">
    <NFormItem path="mobile">
      <NInput v-model:value="model.mobile" :placeholder="$t('page.login.common.userNamePlaceholder')" />
    </NFormItem>
    <NFormItem path="password">
      <NInput
        v-model:value="model.password"
        type="password"
        show-password-on="click"
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      />
    </NFormItem>
    <NSpace vertical :size="24">
      <NButton type="primary" size="large" :disabled="loading" round block :loading="loading" @click="handleSubmit">
        {{ $t('common.login') }}
      </NButton>
    </NSpace>
  </NForm>
</template>

<style scoped></style>
